package com.example.admin.mybledemo.ota;

import android.os.Handler;
import android.os.Looper;

import cn.com.heaton.blelibrary.ble.BleLog;

import com.example.admin.mybledemo.BleRssiDevice;

import java.util.List;

/**
 * 第二阶段数据传输管理器
 * 完全按照Flutter端的_delayedRecursiveCall逻辑实现
 */
public class Phase2DataManager {
    
    private static final String TAG = "Phase2DataManager";
    
    private Phase2Protocol phase2Protocol;
    private BleRssiDevice targetDevice;
    private BleCommunicator bleCommunicator;
    private Phase2DataListener listener;
    private Handler mainHandler;
    
    public interface Phase2DataListener {
        void onProgressChanged(int progress, int total);
        void onLog(String message);
        void onError(String error);
        void onCompleted();
        void scheduleNextBlock(Runnable runnable);
    }
    
    public Phase2DataManager(BleRssiDevice targetDevice, BleCommunicator bleCommunicator, 
                           List<String> otaContent, Phase2DataListener listener) {
        this.targetDevice = targetDevice;
        this.bleCommunicator = bleCommunicator;
        this.listener = listener;
        this.mainHandler = new Handler(Looper.getMainLooper());
        
        // 初始化Phase2Protocol
        this.phase2Protocol = new Phase2Protocol(otaContent);
    }
    
    /**
     * 开始第二阶段数据传输（对应Flutter的_startOtaSecondStep）
     */
    public void startOtaSecondStep() {
        if (listener != null) {
            listener.onLog("开始ota第二步");
        }
        
        phase2Protocol.startOtaSecondStep();
        
        // 延迟100ms后开始递归调用（对应Flutter的Future.delayed）
        mainHandler.postDelayed(this::delayedRecursiveCall, 100);
    }
    
    /**
     * 延迟递归调用（对应Flutter的_delayedRecursiveCall）
     */
    private void delayedRecursiveCall() {
        if (phase2Protocol.getCurrentPosition() == 0) {
            // 发送OTA开始命令
            if (listener != null) {
                listener.onLog("sendOtaStart...");
            }
            sendOtaStart();
        } else {
            // 检查当前位置
            String blockStr = phase2Protocol.getCurrentLine();
            int curPos = phase2Protocol.getCurrentPosition();
            
            if (listener != null) {
                listener.onLog("_startOtaSecondStep curStr " + blockStr + ", curPos:" + curPos);
            }
            
            if (phase2Protocol.isCompleted()) {
                // 发送结束命令
                sendEndOta();
            } else if (blockStr.startsWith("@")) {
                // 发送块命令
                sendBlockCmd();
            } else {
                // 发送块数据
                sendBlockData();
            }
        }
    }
    
    /**
     * 发送OTA开始命令（对应Flutter的_sendOtaStart）
     */
    private void sendOtaStart() {
        // 从配置中获取凭证码，如果没有则使用默认值
        String creditCode = getCreditCode();
        byte[] startCommand = phase2Protocol.buildOtaStartCommand(creditCode);
        
        if (listener != null) {
            listener.onLog("发送OTA开始命令: " + bytesToHexString(startCommand));
        }
        
        bleCommunicator.writeCharacteristic(targetDevice, 
            OtaProtocol.BOOT_OTA_SERVICE_UID, 
            OtaProtocol.BOOT_OTA_CMD_UID, 
            startCommand);
    }
    
    /**
     * 发送块命令（对应Flutter的_sendBlockCmd）
     */
    private void sendBlockCmd() {
        byte[] blockCommand = phase2Protocol.buildBlockCommand();
        if (blockCommand != null) {
            if (listener != null) {
                listener.onLog("发送块命令: " + bytesToHexString(blockCommand));
            }
            
            bleCommunicator.writeCharacteristic(targetDevice, 
                OtaProtocol.BOOT_OTA_SERVICE_UID, 
                OtaProtocol.BOOT_OTA_CMD_UID, 
                blockCommand);
            
            // 移动到下一个位置
            phase2Protocol.nextPosition();
        }
    }
    
    /**
     * 发送块数据（对应Flutter的_sendBlockData）
     */
    private void sendBlockData() {
        byte[] blockData = phase2Protocol.buildBlockData();
        if (blockData != null) {
            if (listener != null) {
                listener.onLog("发送块数据，大小: " + blockData.length + " 字节");
            }
            
            bleCommunicator.writeCharacteristic(targetDevice, 
                OtaProtocol.BOOT_OTA_SERVICE_UID, 
                OtaProtocol.BOOT_OTA_CMD_UID, 
                blockData);
            
            // 移动到下一个位置（块数据需要跳过已发送的行数）
            int size = Math.min(32, phase2Protocol.getTotalLines() - phase2Protocol.getCurrentPosition());
            phase2Protocol.nextPositionForBlockData(size);
        }
    }
    
    /**
     * 发送结束命令（对应Flutter的_sendEndOta）
     */
    private void sendEndOta() {
        // 延迟200ms后发送结束命令（对应Flutter的Future.delayed）
        mainHandler.postDelayed(() -> {
            if (listener != null) {
                listener.onLog("_sendEndOta...");
            }
            
            byte[] endCommand = phase2Protocol.buildEndCommand();
            bleCommunicator.writeCharacteristic(targetDevice, 
                OtaProtocol.BOOT_OTA_SERVICE_UID, 
                OtaProtocol.BOOT_OTA_CMD_UID, 
                endCommand);
        }, 200);
    }
    
    /**
     * 处理写入成功响应（对应Flutter的_writeCmdToBootCharacteristic的then回调）
     */
    public void onWriteSuccess(byte[] data) {
        // 更新进度
        int progress = phase2Protocol.getProgress();
        if (listener != null) {
            listener.onProgressChanged(progress, 100);
            listener.onLog("写入指令(数据): " + bytesToHexString(data));
        }
        
        // 检查是否是结束命令（对应Flutter的data == _endCmd）
        if (isEndCommand(data)) {
            if (listener != null) {
                listener.onLog("所有数据写入完成");
                listener.onCompleted();
            }
        } else {
            // 继续递归调用
            if (listener != null) {
                listener.scheduleNextBlock(this::delayedRecursiveCall);
            }
        }
    }
    
    /**
     * 处理写入失败
     */
    public void onWriteError(String error) {
        if (listener != null) {
            listener.onLog("二阶段写入报错: " + error);
            listener.onError(error);
        }
    }
    
    /**
     * 处理写入超时
     */
    public void onWriteTimeout() {
        if (listener != null) {
            listener.onLog("二阶段写入超时");
            listener.onError("写入超时");
        }
    }
    
    /**
     * 检查是否是结束命令（对应Flutter的data == _endCmd）
     * Flutter: final List<int> _endCmd = [01, 03];
     */
    private boolean isEndCommand(byte[] data) {
        // 与Flutter端完全一致：检查是否是结束命令 [0x01, 0x03]
        return data.length == 2 && data[0] == 0x01 && data[1] == 0x03;
    }
    
    /**
     * 获取当前进度
     */
    public int getProgress() {
        return phase2Protocol.getProgress();
    }
    
    /**
     * 获取当前位置
     */
    public int getCurrentPosition() {
        return phase2Protocol.getCurrentPosition();
    }
    
    /**
     * 获取总行数
     */
    public int getTotalLines() {
        return phase2Protocol.getTotalLines();
    }
    
    /**
     * 检查是否正在OTA中
     */
    public boolean isOtaing() {
        return phase2Protocol.isOtaing();
    }
    
    /**
     * 获取凭证码
     */
    private String getCreditCode() {
        // 这里应该从配置中获取，暂时使用默认值
        // TODO: 从OtaConfig或其他配置源获取凭证码
        return "524d4943"; // 默认凭证码
    }
    
    /**
     * 字节数组转十六进制字符串
     */
    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x ", b & 0xFF));
        }
        return sb.toString().trim();
    }
} 